package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.ExhaustGasWarningMapper;
import com.bf.electroplating.pojo.entity.ExhaustGasWarning;
import com.bf.electroplating.pojo.entity.ExhaustGasWarningConfig;
import com.bf.electroplating.pojo.entity.PubParamDictionary;
import com.bf.electroplating.pojo.entity.WasteGasMonitoring;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.pojo.vo.exhaustGasWarning.ExhaustGasWarningHandleDTO;
import com.bf.electroplating.pojo.vo.exhaustGasWarning.ExhaustGasWarningQueryDTO;
import com.bf.electroplating.pojo.vo.exhaustGasWarning.ExhaustGasWarningStatsVO;
import com.bf.electroplating.pojo.vo.exhaustGasWarning.ExhaustGasWarningVO;
import com.bf.electroplating.service.IExhaustGasWarningConfigService;
import com.bf.electroplating.service.IExhaustGasWarningService;
import com.bf.electroplating.service.PubAttachmentService;
import com.bf.electroplating.service.PubParamDictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 废气处理设施监控预警服务实现类
 */
@Slf4j
@Service
public class ExhaustGasWarningServiceImpl extends ServiceImpl<ExhaustGasWarningMapper, ExhaustGasWarning> 
        implements IExhaustGasWarningService {

    @Autowired
    private IExhaustGasWarningConfigService exhaustGasWarningConfigService;
    @Autowired
    private PubAttachmentService pubAttachmentService;
    @Autowired
    private PubParamDictionaryService pubParamDictionaryService;

    @Override
    public void checkAndGenerateWarning(WasteGasMonitoring wasteGasMonitoring, 
                                        BigDecimal monitoringValue, 
                                        String factorUnit) {
        log.info("开始检查废气预警，设备：{}，监测值：{}，因子单位：{}", 
                wasteGasMonitoring.getDeviceName(), monitoringValue, factorUnit);

        try {
            // 1. 查询该设备的预警配置
            LambdaQueryWrapper<ExhaustGasWarningConfig> configWrapper = new LambdaQueryWrapper<>();
            configWrapper.eq(ExhaustGasWarningConfig::getDeviceName, wasteGasMonitoring.getDeviceName())
                    .eq(ExhaustGasWarningConfig::getMonitoringFactor, wasteGasMonitoring.getMonitoringFactor())
                    .eq(ExhaustGasWarningConfig::getFactorUnit, factorUnit)
                    .eq(ExhaustGasWarningConfig::getIsEnabled, "1")
                    .eq(ExhaustGasWarningConfig::getDelFlag, "0");

            List<ExhaustGasWarningConfig> configList = exhaustGasWarningConfigService.list(configWrapper);
            
            if (configList.isEmpty()) {
                log.debug("未找到设备 {} 的预警配置，跳过预警检查", wasteGasMonitoring.getDeviceName());
                return;
            }

            // 2. 遍历配置，检查是否触发预警
            for (ExhaustGasWarningConfig config : configList) {
                boolean isWarning = false;
                String warningType = "";
                String warningProblem = "";

                // 检查上限阈值
                if (config.getUpperThreshold() != null && 
                    monitoringValue.compareTo(config.getUpperThreshold()) > 0) {
                    isWarning = true;
                    warningType = "上限超标";
                    warningProblem = String.format("监测值 %.2f 超过上限阈值 %.2f", 
                            monitoringValue, config.getUpperThreshold());
                }
                
                // 检查下限阈值
                if (config.getLowerThreshold() != null && 
                    monitoringValue.compareTo(config.getLowerThreshold()) < 0) {
                    isWarning = true;
                    warningType = "下限超标";
                    warningProblem = String.format("监测值 %.2f 低于下限阈值 %.2f", 
                            monitoringValue, config.getLowerThreshold());
                }

                // 3. 如果触发预警，生成预警记录
                if (isWarning) {
                    generateWarningRecord(wasteGasMonitoring, config, monitoringValue, 
                                        warningType, warningProblem);
                }
            }

        } catch (Exception e) {
            log.error("检查废气预警时发生异常，设备：{}，监测值：{}", 
                    wasteGasMonitoring.getDeviceName(), monitoringValue, e);
        }
    }

    /**
     * 生成预警记录
     */
    private void generateWarningRecord(WasteGasMonitoring wasteGasMonitoring, 
                                      ExhaustGasWarningConfig config, 
                                      BigDecimal monitoringValue, 
                                      String warningType, 
                                      String warningProblem) {
        try {
            // 检查是否已存在相同的预警记录（避免重复预警）
            LambdaQueryWrapper<ExhaustGasWarning> warningWrapper = new LambdaQueryWrapper<>();
            warningWrapper.eq(ExhaustGasWarning::getCompanyId, wasteGasMonitoring.getCompanyId())
                    .eq(ExhaustGasWarning::getDeviceName, wasteGasMonitoring.getDeviceName())
                    .eq(ExhaustGasWarning::getMonitoringFactor, wasteGasMonitoring.getMonitoringFactor())
                    .eq(ExhaustGasWarning::getWarningType, warningType)
                    .eq(ExhaustGasWarning::getHandleStatus, "0") // 未处理
                    .eq(ExhaustGasWarning::getDelFlag, "0")
                    .orderByDesc(ExhaustGasWarning::getWarningTime)
                    .last("LIMIT 1");

            ExhaustGasWarning existingWarning = this.getOne(warningWrapper);
            
            // 如果存在未处理的相同预警，且时间间隔小于1小时，则不重复生成
            if (existingWarning != null && 
                existingWarning.getWarningTime().isAfter(LocalDateTime.now().minusHours(1))) {
                log.debug("设备 {} 已存在未处理的相同预警，跳过生成", wasteGasMonitoring.getDeviceName());
                return;
            }

            // 创建新的预警记录
            ExhaustGasWarning warning = new ExhaustGasWarning();
            warning.setId(UUID.randomUUID().toString().replace("-", ""));
            warning.setCompanyId(wasteGasMonitoring.getCompanyId());
            warning.setCompanyName(wasteGasMonitoring.getCompanyName());
            warning.setParkId(wasteGasMonitoring.getParkId());
            warning.setParkName(""); // 需要根据实际情况设置
            warning.setExhaustGasType("废气处理设施"); // 默认类型
            warning.setMonitoringFactor(wasteGasMonitoring.getMonitoringFactor());
            warning.setFactorUnit(config.getFactorUnit());
            warning.setMonitoringValue(monitoringValue);
            warning.setThresholdValue(config.getUpperThreshold() != null ? 
                    config.getUpperThreshold() : config.getLowerThreshold());
            warning.setWarningType(warningType);
            warning.setWarningLevel(config.getWarningLevel());
            warning.setWarningProblem(warningProblem);
            warning.setWarningTime(LocalDateTime.now());
            warning.setHandleStatus("0"); // 未处理
            warning.setHandleBy(null);
            warning.setHandleTime(null);
            warning.setHandleResult(null);
            warning.setHandleRemark(null);
            warning.setDeviceId(""); // 需要根据实际情况设置
            warning.setDeviceName(wasteGasMonitoring.getDeviceName());
            warning.setDataSource("HJ212在线监测");
            warning.setCreateBy("系统自动生成");
            warning.setCreateTime(LocalDateTime.now());
            warning.setUpdateBy("系统自动生成");
            warning.setUpdateTime(LocalDateTime.now());
            warning.setDelFlag("0");

            // 保存预警记录
            boolean result = this.save(warning);
            
            if (result) {
                log.info("废气预警记录生成成功，设备：{}，预警类型：{}，监测值：{}", 
                        wasteGasMonitoring.getDeviceName(), warningType, monitoringValue);
            } else {
                log.error("废气预警记录生成失败，设备：{}，预警类型：{}", 
                        wasteGasMonitoring.getDeviceName(), warningType);
            }

        } catch (Exception e) {
            log.error("生成废气预警记录时发生异常，设备：{}，预警类型：{}", 
                    wasteGasMonitoring.getDeviceName(), warningType, e);
        }
    }

    @Override
    public Page<ExhaustGasWarningVO> pageList(ExhaustGasWarningQueryDTO queryDTO) {
        log.info("分页查询废气预警，查询条件：{}", queryDTO);
        
        Page<ExhaustGasWarning> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        LambdaQueryWrapper<ExhaustGasWarning> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExhaustGasWarning::getDelFlag, "0")
                .like(StringUtils.hasText(queryDTO.getCompanyId()), ExhaustGasWarning::getCompanyId, queryDTO.getCompanyId())
                .like(StringUtils.hasText(queryDTO.getCompanyName()), ExhaustGasWarning::getCompanyName, queryDTO.getCompanyName())
                .like(StringUtils.hasText(queryDTO.getParkId()), ExhaustGasWarning::getParkId, queryDTO.getParkId())
                .like(StringUtils.hasText(queryDTO.getParkName()), ExhaustGasWarning::getParkName, queryDTO.getParkName())
                .like(StringUtils.hasText(queryDTO.getExhaustGasType()), ExhaustGasWarning::getExhaustGasType, queryDTO.getExhaustGasType())
                .like(StringUtils.hasText(queryDTO.getMonitoringFactor()), ExhaustGasWarning::getMonitoringFactor, queryDTO.getMonitoringFactor())
                .eq(StringUtils.hasText(queryDTO.getWarningType()), ExhaustGasWarning::getWarningType, queryDTO.getWarningType())
                .eq(StringUtils.hasText(queryDTO.getWarningLevel()), ExhaustGasWarning::getWarningLevel, queryDTO.getWarningLevel())
                .eq(StringUtils.hasText(queryDTO.getHandleStatus()), ExhaustGasWarning::getHandleStatus, queryDTO.getHandleStatus())
                .like(StringUtils.hasText(queryDTO.getHandleBy()), ExhaustGasWarning::getHandleBy, queryDTO.getHandleBy())
                .like(StringUtils.hasText(queryDTO.getDeviceName()), ExhaustGasWarning::getDeviceName, queryDTO.getDeviceName())
                .like(StringUtils.hasText(queryDTO.getDataSource()), ExhaustGasWarning::getDataSource, queryDTO.getDataSource())
                                .orderByDesc(ExhaustGasWarning::getWarningTime);
                if (!StringUtils.isEmpty(queryDTO.getWarningStartTime())) {
                    LocalDateTime startTime = LocalDate.parse(queryDTO.getWarningStartTime()).atTime(0,0,0);
                    LocalDateTime endTime =LocalDate.parse(queryDTO.getWarningStartTime()).atTime(23,59,59);
                    wrapper.between( ExhaustGasWarning::getWarningTime, startTime,endTime);
                }
        Page<ExhaustGasWarning> warningPage = this.page(page, wrapper);
        
        // 转换为VO
        Page<ExhaustGasWarningVO> voPage = new Page<>();
        BeanUtils.copyProperties(warningPage, voPage, "records");
        
        List<ExhaustGasWarningVO> voList = warningPage.getRecords().stream()
                .map(this::convertToVO)
                .toList();

        voPage.setRecords(voList);
        
        log.info("分页查询废气预警完成，共{}条记录", voList.size());
        return voPage;
    }

    @Override
    public ExhaustGasWarningVO getDetail(String id) {
        log.info("获取废气预警详情，ID：{}", id);
        
        ExhaustGasWarning warning = this.getById(id);
        if (warning == null) {
            log.warn("废气预警不存在，ID：{}", id);
            return null;
        }
        
        return convertToVO(warning);
    }

    @Override
    public Boolean handleWarning(ExhaustGasWarningHandleDTO handleDTO) {
        log.info("处置废气预警，数据：{}", handleDTO);
        
        try {
            ExhaustGasWarning warning = this.getById(handleDTO.getId());
            if (warning == null) {
                log.warn("废气预警不存在，ID：{}", handleDTO.getId());
                return false;
            }
            
            if ("1".equals(warning.getHandleStatus())) {
                log.warn("废气预警已处理，ID：{}", handleDTO.getId());
                return false;
            }
            
            warning.setHandleStatus("1");
//            warning.setHandleBy(handleDTO.getHandleBy());
            warning.setHandleTime(LocalDateTime.now());
            warning.setHandleResult("1");
            warning.setHandleRemark(handleDTO.getHandleRemark());
//            warning.setUpdateBy(handleDTO.getHandleBy());
            warning.setUpdateTime(LocalDateTime.now());
            pubAttachmentService.saveWholeAttachmentRel ( handleDTO.getAttFile () , handleDTO.getId () , AttModuleEnums.WARN_SOLVE.getCode () );

            boolean result = this.updateById(warning);
            log.info("处置废气预警{}，ID：{}", result ? "成功" : "失败", handleDTO.getId());
            return result;
            
        } catch (Exception e) {
            log.error("处置废气预警失败", e);
            return false;
        }
    }

    @Override
    public Boolean batchHandleWarning(String[] ids, ExhaustGasWarningHandleDTO handleDTO) {

            return false;
    }

    @Override
    public Boolean deleteWarning(String id) {
        log.info("删除废气预警，ID：{}", id);
        
        try {
            ExhaustGasWarning warning = this.getById(id);
            if (warning == null) {
                log.warn("废气预警不存在，ID：{}", id);
                return false;
            }
            
            warning.setDelFlag("1");
            warning.setUpdateBy("系统管理员");
            warning.setUpdateTime(LocalDateTime.now());
            
            boolean result = this.updateById(warning);
            log.info("删除废气预警{}，ID：{}", result ? "成功" : "失败", id);
            return result;
            
        } catch (Exception e) {
            log.error("删除废气预警失败", e);
            return false;
        }
    }

    @Override
    public Boolean batchDeleteWarning(String[] ids) {
        log.info("批量删除废气预警，IDs：{}", Arrays.toString(ids));
        
        try {
            List<ExhaustGasWarning> warningList = this.listByIds(Arrays.asList(ids));
            if (warningList.isEmpty()) {
                log.warn("未找到要删除的废气预警");
                return false;
            }
            
            warningList.forEach(warning -> {
                warning.setDelFlag("1");
                warning.setUpdateBy("系统管理员");
                warning.setUpdateTime(LocalDateTime.now());
            });
            
            boolean result = this.updateBatchById(warningList);
            log.info("批量删除废气预警{}，共{}条", result ? "成功" : "失败", warningList.size());
            return result;
            
        } catch (Exception e) {
            log.error("批量删除废气预警失败", e);
            return false;
        }
    }

    @Override
    public ExhaustGasWarningStatsVO getWarningStats() {
        log.info("获取废气预警统计信息");
        
        try {
            ExhaustGasWarningStatsVO stats = new ExhaustGasWarningStatsVO();
            
            // 基础统计
            LambdaQueryWrapper<ExhaustGasWarning> totalWrapper = new LambdaQueryWrapper<>();
            totalWrapper.eq(ExhaustGasWarning::getDelFlag, "0");
            stats.setTotalCount(this.count(totalWrapper));
            
            LambdaQueryWrapper<ExhaustGasWarning> unhandledWrapper = new LambdaQueryWrapper<>();
            unhandledWrapper.eq(ExhaustGasWarning::getDelFlag, "0").eq(ExhaustGasWarning::getHandleStatus, "0");
            stats.setUnhandledCount(this.count(unhandledWrapper));
            
            LambdaQueryWrapper<ExhaustGasWarning> handledWrapper = new LambdaQueryWrapper<>();
            handledWrapper.eq(ExhaustGasWarning::getDelFlag, "0").eq(ExhaustGasWarning::getHandleStatus, "1");
            stats.setHandledCount(this.count(handledWrapper));
            
            // 预警级别统计
            LambdaQueryWrapper<ExhaustGasWarning> level1Wrapper = new LambdaQueryWrapper<>();
            level1Wrapper.eq(ExhaustGasWarning::getDelFlag, "0").eq(ExhaustGasWarning::getWarningLevel, "1");
            stats.setLevel1Count(this.count(level1Wrapper));
            
            LambdaQueryWrapper<ExhaustGasWarning> level2Wrapper = new LambdaQueryWrapper<>();
            level2Wrapper.eq(ExhaustGasWarning::getDelFlag, "0").eq(ExhaustGasWarning::getWarningLevel, "2");
            stats.setLevel2Count(this.count(level2Wrapper));
            
            LambdaQueryWrapper<ExhaustGasWarning> level3Wrapper = new LambdaQueryWrapper<>();
            level3Wrapper.eq(ExhaustGasWarning::getDelFlag, "0").eq(ExhaustGasWarning::getWarningLevel, "3");
            stats.setLevel3Count(this.count(level3Wrapper));
            
            // 时间统计
            LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            LambdaQueryWrapper<ExhaustGasWarning> todayWrapper = new LambdaQueryWrapper<>();
            todayWrapper.eq(ExhaustGasWarning::getDelFlag, "0").ge(ExhaustGasWarning::getWarningTime, today);
            stats.setTodayCount(this.count(todayWrapper));
            
            LocalDateTime weekStart = today.minusDays(7);
            LambdaQueryWrapper<ExhaustGasWarning> weekWrapper = new LambdaQueryWrapper<>();
            weekWrapper.eq(ExhaustGasWarning::getDelFlag, "0").ge(ExhaustGasWarning::getWarningTime, weekStart);
            stats.setWeekCount(this.count(weekWrapper));
            
            LocalDateTime monthStart = today.minusDays(30);
            LambdaQueryWrapper<ExhaustGasWarning> monthWrapper = new LambdaQueryWrapper<>();
            monthWrapper.eq(ExhaustGasWarning::getDelFlag, "0").ge(ExhaustGasWarning::getWarningTime, monthStart);
            stats.setMonthCount(this.count(monthWrapper));
            
            log.info("获取废气预警统计信息完成");
            return stats;
            
        } catch (Exception e) {
            log.error("获取废气预警统计信息失败", e);
            return new ExhaustGasWarningStatsVO();
        }
    }

    /**
     * 转换为VO
     */
    private ExhaustGasWarningVO convertToVO(ExhaustGasWarning warning) {
        ExhaustGasWarningVO vo = new ExhaustGasWarningVO();
        BeanUtils.copyProperties(warning, vo);
        
        // 设置废气类型名称
        if ("废气处理设施".equals(warning.getExhaustGasType())) {
            vo.setExhaustGasTypeName("废气处理设施");
        }
        
        // 设置预警类型名称

        vo.setWarningTypeName(pubParamDictionaryService.getNameByModuleAndCode("YJLX", warning.getWarningType()));
        
        // 设置预警级别名称
        if ("1".equals(warning.getWarningLevel())) {
            vo.setWarningLevelName("一级预警");
        } else if ("2".equals(warning.getWarningLevel())) {
            vo.setWarningLevelName("二级预警");
        } else if ("3".equals(warning.getWarningLevel())) {
            vo.setWarningLevelName("三级预警");
        }
        
        // 设置处置状态名称
        if ("0".equals(warning.getHandleStatus())) {
            vo.setHandleStatusName("未处理");
        } else if ("1".equals(warning.getHandleStatus())) {
            vo.setHandleStatusName("已处理");
        }
        vo.setAttFile ( pubAttachmentService.getWholeFile ( warning.getId () , AttModuleEnums.WARN_SOLVE.getCode () ) );

        return vo;
    }
}